package com.bestom.t9mod.commons.utils;

public class DataConversion {

    //将bit位数值由1变为0
    public int computRegOpenByteData(int data,int locate){

        if (locate==0){
            return  (data & 0x7F);
        }else if (locate==1){
            return  (data & 0xBF);
        }else if (locate==2){
            return  (data & 0xDF);
        }else if (locate==3){
            return  (data & 0xEF);
        }else if (locate==4){
            return  (data & 0xF7);
        }else if (locate==5){
            return  (data & 0xFB);
        }else if (locate==6){
            return  (data & 0xFD);
        }else if (locate==7){
            return  (data & 0xFE);
        }
        return data;
    }
    //将bit位数值由0变为1
    public int computRegByteData(int data, int locate){
        if (locate==0){
            return  (data | 0x80);
        }else if (locate==1){
            return  (data | 0x40);
        }else if (locate==2){
            return  (data | 0x20);
        }else if (locate==3){
            return  (data | 0x10);
        }else if (locate==4){
            return  (data | 0x08);
        }else if (locate==5){
            return  (data | 0x04);
        }else if (locate==6){
            return  (data | 0x02);
        }else if (locate==7){
            return  (data | 0x01);
        }
        return data;
    }

    // 计算十六进制和
    public String makeChecksum(String hexdata) {
        if (hexdata == null || hexdata.equals("")) {
            return "00";
        }
        hexdata = hexdata.replaceAll(" ", "");
        int total = 0;
        int len = hexdata.length();
        if (len % 2 != 0) {
            return "00";
        }
        int num = 0;
        while (num < len) {
            String s = hexdata.substring(num, num + 2);
            total += Integer.parseInt(s, 16);
            num = num + 2;
        }
        return hexInt(total);
    }

    private String hexInt(int total) {
        int a = total / 256;
        int b = total % 256;
        if (a > 255) {
            return hexInt(a) + format(b);
        }
        return format(a) + format(b);
    }

    private String format(int hex) {
        String hexa = Integer.toHexString(hex);
        int len = hexa.length();
        if (len < 2) {
            hexa = "0" + hexa;
        }
        return hexa;
    }
}
